package it.unisalento.appsalento.activity.fragment;

import it.unisalento.R;
import it.unisalento.appsalento.activity.App;
import it.unisalento.appsalento.adapter.NewsAdapter;
import it.unisalento.appsalento.constants.Constants;
import it.unisalento.appsalento.model.Appello;
import it.unisalento.appsalento.model.Notizia;

import java.text.SimpleDateFormat;
import java.util.ArrayList;

import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

/**
 * Fragment che contiene la lista delle news, il pulsante per accedere al
 * libretto, quello per accedere alla lista di appelli e quello per i risultati
 */
public class HomeFragment extends Fragment {
	private ImageButton mLibrettoButton;
	private ImageButton mAppelliButton;
	private ListView mNewsList;
	private TextView mEmptyList;
	private TextView mRisultati;
	private ImageButton mRisultatiButton;

	private NewsAdapter adapter;
	private ArrayList<Notizia> newsList = new ArrayList<Notizia>();
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        LocalBroadcastManager
			.getInstance(getActivity().getApplicationContext())
			.registerReceiver(mUpdateNewsReceiver,
					new IntentFilter(Constants.UPDATE_NEWS_EVENT));
	
		LocalBroadcastManager
			.getInstance(getActivity().getApplicationContext())
			.registerReceiver(mUpdateAppelliButtonReceiver,
					new IntentFilter(Constants.UPDATE_APPELLI_EVENT));
    }

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		View rootView = inflater.inflate(R.layout.fragment_home, container,
				false);

		mLibrettoButton = (ImageButton) rootView.findViewById(R.id.libretto_button);
		mAppelliButton = (ImageButton) rootView.findViewById(R.id.appelli_button);
		mRisultati = (TextView) rootView.findViewById(R.id.risultati_button_number);
		mRisultatiButton = (ImageButton) rootView.findViewById(R.id.risultati_button);
		
		refreshAppelliRisultatiButton();
		
		mLibrettoButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				FragmentManager fragmentManager = getFragmentManager();
				fragmentManager.beginTransaction()
						.replace(R.id.content_frame, new LibrettoFragment())
						.addToBackStack(null)
						.commit();
			}
		});
		
		mNewsList = (ListView) rootView.findViewById(R.id.news_list);
		mEmptyList = (TextView) rootView.findViewById(R.id.empty_news_list);

		adapter = new NewsAdapter(getActivity(), R.layout.row_news,
				newsList);
		mNewsList.setAdapter(adapter);
		mNewsList.setEmptyView(mEmptyList);

		mNewsList.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {
				Notizia notizia = (Notizia) parent.getItemAtPosition(position);

				Dialog dialog = new Dialog(parent.getContext());
				dialog.setContentView(R.layout.dialog_news);
				dialog.setTitle(notizia.getTitolo());
				
				TextView mTitle = (TextView) dialog
						.findViewById(android.R.id.title);
				mTitle.setTextColor(parent.getResources().getColor(
						R.color.unisalento_text));
				mTitle.setGravity(Gravity.CENTER);
				View mTitleDivider = dialog.findViewById(Resources.getSystem()
						.getIdentifier("titleDivider", "id", "android"));
				mTitleDivider.setBackgroundColor(parent.getResources().getColor(
						R.color.unisalento_text));

				TextView mNotiziaData = (TextView) dialog
						.findViewById(R.id.notizia_data);
				TextView mNotiziaTesto = (TextView) dialog
						.findViewById(R.id.notizia_testo);

				mNotiziaData.setText(new SimpleDateFormat(Constants.DD_MM_YY)
						.format(notizia.getData()));
				mNotiziaTesto.setText(notizia.getTesto());

				dialog.setCancelable(true);
				dialog.show();
			}
		});
		
		Intent intent = new Intent(Constants.UPDATE_NEWS_EVENT);
		LocalBroadcastManager.getInstance(
				App.currentActivity().getApplicationContext()).sendBroadcast(
				intent);

		return rootView;
	}
	
	public void refreshAppelliRisultatiButton() {
		int risultati = 0;
		for (Appello appello : App.appelli) {
			if (appello.getStato().equals(Appello.DA_ACCETTARE)
					|| appello.getStato().equals(Appello.RISULTATO_ACCETTATO)
					|| appello.getStato().equals(Appello.RISULTATO_RIFIUTATO)) {
				risultati ++;
			}
		}
		
		if (risultati == 0) {
			mRisultatiButton.setBackgroundResource(R.drawable.risultati_disabled);
			mRisultati.setVisibility(View.GONE);
		} else {
			mRisultatiButton.setBackgroundResource(R.drawable.risultati);
			mRisultatiButton.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					if (App.risultatiFragment==null){
						App.risultatiFragment = new RisultatiFragment();
					}
					FragmentManager fragmentManager = getFragmentManager();
					fragmentManager.beginTransaction()
							.replace(R.id.content_frame, App.risultatiFragment)
							.addToBackStack(null)
							.commit();
				}
			});
			if (risultati>0) {
				mRisultati.setVisibility(View.VISIBLE);
				mRisultati.setText(risultati+"");
			}
		}
		
		if (App.appelli.size() == 0) {
			mAppelliButton.setBackgroundResource(R.drawable.appelli_disabled);
		} else {
			mAppelliButton.setBackgroundResource(R.drawable.appelli);
			mAppelliButton.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					FragmentManager fragmentManager = getFragmentManager();
					fragmentManager.beginTransaction()
							.replace(R.id.content_frame, new CalendarioFragment())
							.addToBackStack(null)
							.commit();
				}
			});
		}
	}

	private BroadcastReceiver mUpdateNewsReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			newsList.clear();
			newsList.addAll(App.news);
			adapter.notifyDataSetChanged();
		}
	};
	
	private BroadcastReceiver mUpdateAppelliButtonReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			refreshAppelliRisultatiButton();
		}
	};
}
